package com.example.chessbattleplatform.exception_advice;

import cn.hutool.core.util.ArrayUtil;
import com.example.chessbattleplatform.Pojo.Result.WebResult;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 业务 异常拦截
 * RestControllerAdvice REST 控制器建议
 **/
@RestControllerAdvice
@Slf4j
public class BusinessExceptionHandler {

    /***
     * 过期的 JWT 异常
     */
    @ExceptionHandler(ExpiredJwtException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public WebResult<?> businessperson(ExpiredJwtException e) {
        log.info(" JWT 登录过期请重新登录 {}", e.getMessage());
        return WebResult.unauthorized("登录过期请重新登录");
    }


    // 处理@RequestBody参数验证错误
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public WebResult<?> handleValidationExceptions(MethodArgumentNotValidException e) {

        List<String> errors = e.getBindingResult().getFieldErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());

        log.info("MethodArgumentNotValidException RequestBody参数验证错误 errors:{}", errors);
        return WebResult.missingParameter(ArrayUtil.toString(errors));
    }

    // 处理其他验证异常
    @ExceptionHandler(ConstraintViolationException.class)
    public WebResult<?> handleConstraintViolation(ConstraintViolationException e) {

        List<String> errors = e.getConstraintViolations().stream()
                .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
                .collect(Collectors.toList());
        log.info("ConstraintViolationException 处理其他验证异常 errors:{}", errors);
        return WebResult.missingParameter(ArrayUtil.toString(errors));

    }

    /*
     * 在 Spring Boot 3.x 及以上版本中，
     * 当使用方法参数级别的验证（如直接在 @RequestParam 或方法参数上使用 @NotBlank、@NotNull 等注解）时，
     * 如果验证失败，会抛出 HandlerMethodValidationException 而不是 MethodArgumentNotValidException
     */
    @ExceptionHandler(HandlerMethodValidationException.class)
    public WebResult<?> HandlerMethodValidationExceptionViolation(HandlerMethodValidationException e){
        // 获取所有参数验证错误
        List<String> errors = e.getAllErrors().stream()
                .map(MessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        log.info("HandlerMethodValidationException 处理其他验证异常 errors:{}",ArrayUtil.toString(errors));
        return WebResult.missingParameter(ArrayUtil.toString(errors));
    }

}
